package com.zl.dao;

import java.sql.Connection;
import java.sql.ResultSet;

import com.mysql.jdbc.PreparedStatement;
import com.zl.model.BookType;
import com.zl.util.ZLString;

public class BookTypeDao {
	
	//增删改查
	
	/**
	 * 新增图书
	 * @param connection
	 * @param bookType
	 * @return
	 * @throws Exception
	 */
	public static int add(Connection connection, BookType bookType) throws Exception {
		
		String sql = "insert into t_bookType (bookTypeName, bookTypeDesc) values (?,?)";
		
		PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql);
		
		statement.setString(1, bookType.getBookTypeName());
		statement.setString(2, bookType.getBookTypeDesc());
		
		return statement.executeUpdate();
	}
	
	/**
	 * 删除图书类型
	 * @param connection
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public static int delete(Connection connection, String id) throws Exception {

		String sql = "delete from t_bookType where id = ?";
		
		PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql);
		
		statement.setString(1, id);
		
		return statement.executeUpdate();
	}
	
	/**
	 * 修改图书类型
	 * @param connection
	 * @param bookType
	 * @return
	 * @throws Exception
	 */
	public static int update(Connection connection, BookType bookType) throws Exception {

		String sql = "update t_bookType set bookTypeName = ? , bookTypeDesc = ? where id = ?";
		
		PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql);
		
		statement.setString(1, bookType.getBookTypeName());
		statement.setString(2, bookType.getBookTypeDesc());
		statement.setInt(3, bookType.getId());
		
		return statement.executeUpdate();
	}
	
	public static ResultSet select(Connection con, BookType bookType) throws Exception {
		
		StringBuffer buffer = new StringBuffer("select * from t_bookType");
		
		//此处若存在多个条件 则用and连接 后用string的replaceFirst来替换第一个and为where
		if (ZLString.isNotEmpty(bookType.getBookTypeName())) {//图书类型名称不为空
			buffer.append(" where bookTypeName like '%" + bookType.getBookTypeName() + "%'");
		}
		
		PreparedStatement statement = (PreparedStatement) con.prepareStatement(buffer.toString());
		
		return statement.executeQuery();
	}
}
